<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!-- 状态 -->
      <el-radio-group
        @change="onChangeStatus"
        class="filter-item"
        v-model="status"
        size='small'
      >
        <template v-for="item in statusList">
          <el-radio-button 
            :key="item.id" 
            :label="item.id"
          >
          {{item.text}}
          </el-radio-button>
        </template>
      </el-radio-group>
      <!-- 订单时间 -->
      <el-date-picker
        v-model="defaultDate"
        :default-time="['00:00:00','23:59:59']"
        type="daterange"
        range-separator=":"
        size="small"
        class="date-item"
        value-format="yyyy-MM-dd HH:mm:ss"
        start-placeholder="开始时间"
        end-placeholder="结束日期"
        @change="onChangeTime"
      />
      <!-- 供应商 -->
      <el-select
        v-model='query.supplierId'
        clearable
        size='small'
        placeholder='供应商'
        class='filter-item'
        style='width: 100px'
        @change="onQuery"
      >
        <el-option
          v-for='item in suppliers'
          :key='item.id'
          :label='item.text'
          :value='item.id'
        />
      </el-select>
      <!-- 入库方式 -->
      <el-select
        v-if="type == 0"
        v-model='query.wareHousingType'
        clearable
        size='small'
        placeholder='入库方式'
        class='filter-item'
        style='width: 100px'
        @change="onQuery"
      >
        <el-option
          v-for='item in wareHousingTypes'
          :key='item.id'
          :label='item.text'
          :value='item.id'
        />
      </el-select>
      <!-- 药品类型 -->
      <el-select
        v-model='query.drugType'
        clearable
        size='small'
        placeholder='药品类型'
        class='filter-item'
        style='width: 100px'
        @change="onQuery"
      >
        <el-option
          v-for='item in drugTypes'
          :key='item.id'
          :label='item.text'
          :value='item.id'
        />
      </el-select>
      <!-- 付款状态 -->
      <el-select
        v-if="type == 0"
        v-model='query.payStatus'
        clearable
        size='small'
        placeholder='付款状态'
        class='filter-item'
        style='width: 100px'
        @change="onQuery"
      >
        <el-option
          v-for='item in fkList'
          :key='item.id'
          :label='item.text'
          :value='item.id'
        />
      </el-select>
      <!-- 订单号 -->
      <el-input
        v-model="query.wareHousingNo"
        placeholder="输入订单号"
        size='small'
        class="filter-item"
        style="width: 100px"
      />
      <!-- 制单人 -->
      <el-input
        v-if="type == 1"
        v-model="query.createUserName"
        placeholder="制单人"
        size='small'
        class="filter-item"
        style="width: 100px"
      />
      <!-- 查询按钮 -->
      <el-button
        class="filter-item"
        size="mini"
        type="success"
        icon="el-icon-search"
        @click="onQuery"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        size="mini"
        type="warning"
        icon="el-icon-refresh-left"
        @click="onResetQuery"
      >
        重置
      </el-button>
    </div>
    <!--表格渲染-->
    <avue-crud
      @sort-change="onSortChange"
      @refresh-change="onRefresh"
      @current-change="onCurrentChange"
      @size-change="onSizeChange"
      v-loading="loading"
      :option="options"
      :page="page"
      :data="data"
    >
      <!-- 列自定义 -->
      <template slot-scope="scope" slot="wareHousingType">
        <div>
          <housingType :wareHousingType="scope.row.wareHousingType" />
        </div>
      </template>
      <template slot-scope="scope" slot="status">
        <div>
          <housingStatus :value="scope.row.status" />
        </div>
      </template>
      <template slot-scope="scope" slot="orderTotal">
        <span>{{ formatMoney(scope.row.orderTotal, 2) }}</span>
      </template>
      <template slot-scope="scope" slot="warehousingTime">
        <span>{{ parseTime(scope.row.warehousingTime) }}</span>
      </template>
      <!-- 行操作 -->
      <template slot-scope="scope" slot="menu">
        <template v-if="scope.row.status === 1">
          <el-button
            v-permission="['admin', 'cgjh:edit']"
            @click="onEdit(scope.row)"
            type="text"
          >编辑</el-button>
        </template>
        <template v-if="scope.row.status == 2">
          <el-button
            v-permission="['admin', 'cgjh:pass']"
            @click="showDetail(scope.row)"
            type="text"
          >审核</el-button>
        </template>
        <template v-if="scope.row.status == 4">
          <el-button
            v-permission="['admin', 'cgjh:edit']"
            @click="onEdit(scope.row)"
            type="text"
          >编辑</el-button>
        </template>
        <template v-if="scope.row.status == 6">
          <el-button
            v-permission="['admin', 'cgjh:ok']"
            @click="showDetail(scope.row)"
            type="text"
          >确定</el-button>
        </template>
        <template v-if="scope.row.status == 7 && type == 0">
          <el-button
            v-permission="['admin', 'drugWareHousing:add']"
            @click="onEdit(scope.row)"
            type="text"
          >入库</el-button>
          <el-button
            v-permission="['admin', 'drugWareHousing:cancel']"
            @click="onCancel(scope.row.id)"
            type="text"
          >取消</el-button>
        </template>
        <template v-if="scope.row.status == 7 && type == 1">
          <el-button
            v-permission="['admin', 'cgjh:detail']"
            @click="showDetail(scope.row)"
            type="text"
          >查看</el-button>
        </template>
        <template v-if="scope.row.status == 3 || scope.row.status == 5">
          <template v-if="type === 0">
            <el-button
              v-permission="['admin', 'drugWareHousing:detail']"
              @click="showDetail(scope.row)"
              type="text"
            >查看</el-button>
          </template>
          <template v-if="type === 1">
            <el-button
              v-permission="['admin', 'cgjh:detail']"
              @click="showDetail(scope.row)"
              type="text"
            >查看</el-button>
          </template>
        </template>
        <template v-if="scope.row.status < 3 || scope.row.status == 4 || scope.row.status == 6">
          <template v-if="type === 0">
            <el-button
              v-permission="['admin', 'drugWareHousing:cancel']"
              @click="onCancel(scope.row.id)"
              type="text"
            >取消</el-button>
          </template>
          <template v-if="type === 1">
            <el-button
              v-permission="['admin', 'cgjh:cancel']"
              @click="onCancel(scope.row.id)"
              type="text"
            >取消</el-button>
          </template>
        </template>
      </template>
      <!-- 操作栏 -->
      <template slot="menuLeft">
        <avueOperation :permissions="permission" />
      </template>
    </avue-crud>
    <!-- 新增入库 -->
    <el-dialog
      :width="dialogWidth"
      append-to-body 
      top="10vh"
      :title="type == 0 ? '入库信息':'采购计划'"
      :close-on-click-modal="false"
      :visible.sync="showDialog"
    >
      <drugWareInfo
        v-if="showDialog"
        :operation="operation"
        :warehousingId="warehousingId"
        ref="wareInfo"
        @close="showDialog=false"
        @success="onSuccess"
        :type="type"
      >
      </drugWareInfo>
    </el-dialog>
    <!-- 导出 -->
    <exportWareHousing
      :type="type"
      ref="export"
    />
    <!-- 导入 -->
    <importWareHousing
      @success="onSuccess"
      ref="importWare"
      :type="type"
    >
    </importWareHousing>
  </div>
</template>

<script>
import { cancelWarehousing, getSuppliers, getList, outDetail } from '@/api/storageRoom/drugWareHousing';
import { purchaseOption, wareOption } from '@/const/drugWareHousing';
import avueOperation from '@crud/avue.operation';
import housingType from './module/housingType';
import drugWareInfo from './module/info';
import { parseTime, formatMoney } from "@/utils/index";
import { mapGetters } from 'vuex';
import exportWareHousing from './module/export';
import importWareHousing from './module/import';
import housingStatus from "./module/status";

export default {
  name: "drugWareHousing",
  props: {
    // 0-入库, 1-采购计划
    type: {
      type: Number,
      default: 0
    }
  },
  components: { 
    housingType,
    drugWareInfo,
    exportWareHousing,
    importWareHousing,
    housingStatus,
    avueOperation
  },
  data() {
    return {
      drugTypes: [
        { id: 7, text: "西药及中成药" },
        { id: 1, text: "中药饮片" },
        { id: 2, text: "颗粒剂" },
      ],
      fkList: [
        { id: 0, text: "未付款" },
        { id: 1, text: "已付款" },
      ],
      query: {
        wareHousingNo: null,
        status: null,
        wareHousingType: null,
        startTime: null,
        endTime: null,
        supplierId: null,
        drugType: null,
        payStatus: null,
        createUserName: null,
        createStartTime: null,
        createEndTime: null,
        type: null,
        sort: null,
      },
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      data: [],
      defaultDate: null,
      ddefaultDate: null,
      dstartTime:null,
      dendTime:null,
      showDialog: false,
      operation: 0,
      warehousingId: 0,
      suppliers: [],
      status: 0,
      loading: false
    }
  },
  computed: {
    ...mapGetters(["wareHousingTypes"]),
    dialogWidth() {
      return window.innerWidth * 0.9 + "px";
    },
    options() {
      if(this.type == 1) {
        return purchaseOption;
      }
      return wareOption;
    },
    permission() {
      if(this.type == 0) {
        return [
          {
            type: "add",
            name: "新增入库",
            position: 1,
            permission: ['admin', 'drugWareHousing:add'],
            handleClick: "onAdd"
          }, {
            type: "download",
            name: "导入入库",
            position: 1,
            permission: ['admin', 'drugWareHousing:batchImport'],
            handleClick: "onImport"
          }, {
            type: "download",
            name: "导出入库",
            position: 1,
            permission: ['admin', 'drugWareHousing:download'],
            handleClick: "onDownload"
          }, {
            type: "download",
            name: "导出入库清单",
            position: 1,
            permission: ['admin', 'drugWareHousing:detailed'],
            handleClick: "onDetailed"
          }
        ]
      }
      return [
          {
            type: "add",
            name: "新增采购计划",
            position: 1,
            permission: ['admin', 'cgjh:add'],
            handleClick: "onAdd"
          }, {
            type: "download",
            name: "导入采购计划",
            position: 1,
            permission: ['admin', 'cgjh:batchImport'],
            handleClick: "onImport"
          }
        ];
    },
    statusList() {
      if(this.type == 1) {
        return [
          {id: 0, text: '全部'},
          {id: 1, text: '待提交'},
          {id: 2, text: '待审核'},
          {id: 6, text: '待确定'},
          {id: 4, text: '已驳回'},
          {id: 5, text: '已取消'},
        ];
      }
      return [
        {id: 0, text: '全部'},
        {id: 7, text: '待入库'},
        {id: 3, text: '已入库'},
      ];
    }
  },
  mounted() {
    this.onResetQuery();
    this._getSuppliers();
  },
  methods: {
    parseTime, formatMoney,
    showDetail(row) {
      this.operation = row.status;
      this.warehousingId = row.id;
      this.showDialog = true;
    },
    statusByText(status) {
      return this.statusList[status - 1].text;
    },
    onChangeTime() {
      if(this.defaultDate && this.defaultDate.length) {
        if(this.type == 0) {
          this.query.startTime = this.defaultDate[0];
          this.query.endTime = this.defaultDate[1];
        } else {
          this.query.createStartTime = this.defaultDate[0];
          this.query.createEndTime = this.defaultDate[1];
        }
      } else {
        if(this.type == 0) {
          this.query.startTime = null;
          this.query.endTime = null;
        } else {
          this.query.createStartTime = null;
          this.query.createEndTime = null;
        }
        
      }
      this.onQuery();
    },
    onAdd() {
      this.operation = 0;
      this.warehousingId = null;
      this.showDialog = true;
    },
    onDownload(){
      this.$refs.export.show = true;
    },
    onEdit(row) {
      this.operation = row.status;
      this.warehousingId = row.id;
      this.showDialog = true;
    },
    onCancel(id) {
      this.$confirm('是否确认取消该订单?是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        cancelWarehousing(id).then(() => {
          this.onSuccess();
          this.$notify({
            title: "操作成功",
            type: "success"
          });
        });
      }); 
    },
    onSuccess(show) {
      if(!show) {
        this.showDialog = false;
        this.operation = 0;
      }
      this.onQuery();
    },
    onChangeStatus() {
      if(this.status == 0) {
        this.query.status = null;
      } else {
        this.query.status = this.status;
      }
      this.onQuery();
    },
    // 排序
    onSortChange({ prop, order }) {
      let sort = prop.replace(/([A-Z])/g, '_$1').toLowerCase()
      if (order === 'ascending') {
        sort += ',asc'
      } else if (order === 'descending') {
        sort += ',desc'
      } else {
        // 默认排序
        sort = 'id,desc'
      }
      this.query.sort = sort
      this.onRefresh();
    },
    // 查询
    onQuery() {
      this.page.currentPage = 1;
      this.onRefresh();
    },
    // 刷新
    onRefresh() {
      let param = {
        ...this.query,
        size: this.page.pageSize,
        page: this.page.currentPage - 1
      };
      this.loading = true;
      getList(param).then(res => {
        this.loading = false;
        this.data = res.content;
        this.page.total = res.totalElements;
      });
    },
    // 重置查询条件
    onResetQuery() {
      // 订单时间
      this.defaultDate = null;
      this.query.startTime = null;
      this.query.endTime = null;
      // 状态
      this.status = 0;
      this.query.status = null;
      // type: 1-采购单 2-入库单
      if(this.type == 1) {
        this.query.type = 1;
      } else {
        this.query.type = 2;
      }
      // 其它参数
      this.query.wareHousingNo = null;
      this.query.wareHousingType = null;
      this.query.supplierId = null;
      this.query.drugType = null;
      this.query.payStatus = null;
      this.query.sort = 'id,desc';
      this.query.createUserName = null;
      this.query.createStartTime = null;
      this.query.createEndTime = null;
      this.onQuery();
    },
    // 更改页码
    onCurrentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onRefresh();
    },
    // 更改size
    onSizeChange(size) {
      this.page.pageSize = size;
      this.onRefresh();
    },
    onImport() {
      this.$refs.importWare.show = true;
    },
    _getSuppliers() {
      getSuppliers().then(res => {
        res.content.forEach(item => {
          this.suppliers.push({
            id: item.id,
            text: item.supplierName
          });
        });
      });
    },
    onDetailed() {
      if(!this.defaultDate || !this.defaultDate.length) {
        this.$message.error("请选择导出的时间段");
        return;
      }
      let query = this.query;
      let data = {
        ...query,
      };
      outDetail(data);
    }
  }
}
</script>